import { PureComponent } from "react";
import { View, ScrollView } from "@tarojs/components";
import { airportCityListReq } from "@/utils/api";
import tools from "@/utils/tools";
import { ERR_MES } from "@/utils/constant";
import CityItem from "./components/CityItem";

import "./airportList.scss";

class AirportList extends PureComponent {
  state = {
    cityListObj: {},
    letterList: [],
    currentLetter: ""
  };

  componentDidMount() {
    this.getCityList();
  }

  getCityList = () => {
    tools.showLoading();
    airportCityListReq()
      .then((data) => {
        const { result } = data;
        const listObj = this.formatList(result);
        this.setState({
          cityListObj: listObj,
          letterList: Object.keys(listObj),
        });
      })
      .catch(() => {
        tools.showToast(ERR_MES);
      })
      .finally(() => {
        tools.hideLoading();
      });
  };

  formatList = (list) => {
    const obj = {};
    if (list?.length) {
      list.map((ele) => {
        const { firstLetter } = ele;
        if (!obj[firstLetter]) {
          obj[firstLetter] = [];
        }
        obj[firstLetter].push(ele);
      });
    }
    return obj;
  };

  // 改变当前点击的字母，定位到首字母的数据
  handleClickLetter = (letter) => {
    this.setState({ currentLetter: letter });
  }

  render() {
    const { cityListObj, letterList, currentLetter } = this.state;
    return (
      <View className="airport-list-container">
        <ScrollView scrollIntoView={currentLetter} scrollY scrollWithAnimation style={{ height: "100vh" }}>
          {letterList?.map((item) => {
            const cityList = cityListObj[item];
            return <CityItem key={item} label={item} cityList={cityList} />;
          })}
        </ScrollView>
        <View className="letter-container">
          {letterList?.map((item) => {
            return (
              <View key={item} className="letter-item" onClick={() => this.handleClickLetter(item)}>
                {item}
              </View>
            );
          })}
        </View>
      </View>
    );
  }
}

export default AirportList;
